<?php
namespace Common\Model;

class CustomerModel extends \Think\Model{
    
    /**
     * 获取access_token
     */
    public function getToken($appid = '', $secret = ''){
        if(empty($appid) || empty($secret)){
            $this->error = '项目未配置appid或appsecret';
            return false;
        }
        
        $tokenRow = $this->where(array('id'=>1))->find();
        if(empty($tokenRow)) $this->add(array('id'=>1));//无记录则插入一条
        
        if($tokenRow && ($tokenRow['token_time']+7000) > time()){//未过期
            return $tokenRow['token'];
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $jsonstr = curl_request($url);
            $jsondata = json_decode($jsonstr,true);
            if(empty($jsondata['access_token'])){
                $this->error = 'access_token获取失败';
                return false;
            }else{
                $time = time();
                $this->save(array('id'=>1,'token'=>$jsondata['access_token'],'token_time'=>$time));
                return $jsondata['access_token'];
            }
        }
    }
    
}
